package com.transpeed.payservice.pay.unionpay;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;

import org.json.JSONObject;

import com.transpeed.payservice.Utils.JsonUtils;
import com.transpeed.payservice.log.Log;


public class UmsPayPOST {
	public static final String ADD_URL = "http://umspay.izhong.me/netpay-route-server/api/";	
	
	public static String post(HashMap<String, Object> message ) {
		String response = null;
		try {
			// 创建连接
			URL url = new URL(ADD_URL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			connection.connect();
			// POST请求
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			
			Log.Write("发送Json为 \n" + JsonUtils.formatAsJSON(new JSONObject(message).toString()),"UmsPay");
			
			byte [] bytes =  new JSONObject(message).toString().getBytes("UTF-8");
			out.write(bytes);
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "gbk");
				sb.append(lines);
			}

			reader.close();
			// 断开连接
			connection.disconnect();
			response = sb.toString();
			Log.Write("接收Json为 \n" +response,"UmsPay");
			
			Log.Write("接收Json为 \n" + JsonUtils.formatAsJSON(response),"UmsPay");

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return response;
	}
	

}
